package com.cloud.example.config;

import com.cloud.async.business.context.support.StandardAsyncContext;
import com.cloud.async.error.impl.DefaultErrorHandler;
import com.cloud.async.monitor.impl.DefaultResultHandlerMonitor;
import com.cloud.async.result.core.handler.StandardAsyncResultHandler;
import com.cloud.async.retry.DefaultRetryPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.Executor;

/**
 * stater自定义配置非默认自动配置
 * @author chengr 2021-11-12
 */
@SpringBootApplication
public class WebAsyncConfiguration {


    @Autowired
    public Executor executor;

    /**
     * 注入容器两种方式
     * 1.自动注入
     * 启动类上使用@EnableWebAsyncConfiguration
     * 参见yml的中的配置进行配置设置全局等待时间（默认1s）及当前数据Map的长度
     * 必须要有一个线程池 参考{@link com.cloud.example.config.ExecutorConfiguration}
     *
     * 2.手动注入
     * 参见 {@link WebAsyncConfiguration#standardAsyncContext()}
     * 其余均不需配置
     * @return
     */
    @Bean("standardAsyncContext")
    public StandardAsyncContext standardAsyncContext() {

        /**
         * 配置1
         * 使用cls方式进行注入结果解析场景问题切入点
         */
        final StandardAsyncContext standardAsyncContext = new StandardAsyncContext.Builder()
                .executor(executor).dataCapacity(1024)
                .globalTimeout(3000L)
                // 针对结果的获取
                .resultHandler(StandardAsyncResultHandler.class)
                // DefaultErrorHandler.class 针对一场场景的处理
                // DefaultResultHandlerMonitor.class 针对结果获取场景的监控
                // 优先级高于.lifeHandler(new DefaultErrorHandler(), new DefaultResultHandlerMonitor())
                // 默认走cls方式创建
                .lifeHandler(DefaultErrorHandler.class, DefaultResultHandlerMonitor.class)
                // com.cloud.async.business.context.AsyncTaskContext.businessLogic
                // 配置 重试次数 & 结果处理时间
                .retryPolicy(DefaultRetryPolicy.class).build();

        /**
         *  配置2手动注入
         */
        final StandardAsyncContext standardAsyncContext1 = new StandardAsyncContext.Builder()
                .executor(executor).dataCapacity(1024)
                .globalTimeout(3000L)
                .resultHandler(StandardAsyncResultHandler.class)
                // DefaultErrorHandler.class 针对一场场景的处理
                // DefaultResultHandlerMonitor.class 针对结果获取场景的监控
                // 优先级低于.lifeHandler(DefaultErrorHandler.class, DefaultResultHandlerMonitor.class)
                // 参见 {@link AbstractAsyncContext#initialize()}
                .lifeHandler(new DefaultErrorHandler(), new DefaultResultHandlerMonitor())
                // com.cloud.async.business.context.AsyncTaskContext.businessLogic
                // 配置 重试次数 & 结果处理时间
                .retryPolicy(DefaultRetryPolicy.class).build();

        return standardAsyncContext1;
    }


}
